/**
 * 生成范围内随机数
 * @param min
 * @param max
 */
export function randomFloat(min: number, max: number): number {
  return Math.random() * (max - min) + min;
}

/**
 * 生成范围内随机整数
 * @param min
 * @param max
 */
export function randomInt(min: number, max: number): number {
  min = Math.ceil(min);
  max = Math.floor(max);
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

/**
 * 给定一个范围和一个值,如果这个值超过这个范围则返回该范围最大值或最小值
 * @param value
 * @param min
 * @param max
 */
export function clamp(value: number, min: number, max: number): number {
  if (value < min) {
    return min;
  }
  if (value > max) {
    return max;
  }
  return value;
}

/**
 * 给定一个矩形范围,如果这个范围超过限定范围则返回该范围最大值或最小值
 * @param value 坐标:[x1, y1, x2, y2]
 * @param rect 限定矩形范围:[x, y, width, height]
 */
export function clampRect(value: number[], rect: number[]) {
  if (value.length < 4 || rect.length < 4) {
    console.warn("clampRect: value or rect is invalid, 'value' and 'rect' length must be great than 4.");
    return value;
  }
  const minX = rect[0];
  const minY = rect[1];
  const maxX = rect[0] + rect[2];
  const maxY = rect[1] + rect[3];
  return [
    clamp(value[0], minX, maxX),
    clamp(value[1], minY, maxY),
    clamp(value[2], minX, maxX),
    clamp(value[3], minY, maxY),
    // ...
  ];
}

export function round(v: number, fractionDigits: number): number;
export function round(v: number | string | undefined | null, fractionDigits: number): number | null;

/**
 * 四舍五入,并保留指定位数的小数
 * @param v
 * @param fractionDigits 小数位数
 */
export function round(v: number | string | undefined | null, fractionDigits: number): number | null {
  if (v === null || v === undefined || v === "") {
    return null;
  }
  if (typeof v === "string") v = parseFloat(v);
  const n = Math.pow(10, fractionDigits);
  return Math.round(v * n) / n;
}

export function round2(v: number): number;
export function round2(v: number | string | undefined | null): number | null;

export function round2(v: number | string | undefined | null): number | null {
  return round(v, 2);
}

export function round1(v: number): number;
export function round1(v: number | string | undefined | null): number | null;

export function round1(v: number | string | undefined | null): number | null {
  return round(v, 1);
}
